package com.smart.beanfactory;

import com.smart.Car;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * bean生命周期
 * @author chenxingyu
 * @date 2019/8/26 20:51
 */
public class BeanLifeCycle {
    private static void lifeCycleInBeanFactory(){
        //装载配置文件并启动容器
        Resource res = new ClassPathResource("conf/spring666.xml");
        DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
        reader.loadBeanDefinitions(res);


        //向容器中注册MyInstantiationAwareBeanPostProcessor后处理器
        bf.addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());
        //向容器中注册MyBeanPostProcessor后处理器
        bf.addBeanPostProcessor(new MyBeanPostProcessor());

        //第一次从容器中获取car,将触发容器实例化该bean,将引发Bean生命周期方法的调用
        Car car1 = (Car) bf.getBean("car");
        car1.introduce();
        car1.setColor("红色");

        //第二次从容器中获取car,直接从缓存池中获取
        Car car2 = (Car) bf.getBean("car");

        //查看car1和car2是否指向同一引用
        System.out.println("car1==car2:"+(car1==car2));

        //关闭容器
        bf.destroySingletons();
    }

    public static void main(String[] args) {
        lifeCycleInBeanFactory();
    }
}
